<?php 

require_once './Client.php';

$current_dir = dirname(__FILE__);

function parseCommand($data)
{
	return json_decode($data, true);
}

function updateCommand()
{
	//you can do something here
    chdir("/home/church/test");
	exec('git pull > '.$GLOBALS['current_dir'].'log.txt');
	// exec('composer update');
	// exec('npm install');
}

function deleteComposerLock()
{
    chdir("/home/church/test");
	exec('rm -f composer.lock');
}

function migrate()
{
    chdir("/home/church/test");
	exec('php artisan migrate > '.$GLOBALS['current_dir'].'migrate-log.txt');
}

function composerUpdate()
{
    chdir("/home/church/test");
	exec('composer update > '.$GLOBALS['current_dir'].'update-log.txt');
}

$ws = new Client('ws://127.0.0.1:5178?role=solider');

$ws->onMessage = function($client, $frame) use ($ws) {
	$data = parseCommand($frame->data);

	switch ($data['command']) {
		case 'update':
			updateCommand();
			$ws->push(file_get_contents($GLOBALS['current_dir'] . 'log.txt'));
			break;
		case 'delete-composer-lock':
			deleteComposerLock();
			break;
		case 'migrate':
			migrate();
			$ws->push(file_get_contents($GLOBALS['current_dir'] . 'migrate-log.txt'));
			break;
		case 'composer-update':
			composerUpdate();
			$ws->push(file_get_contents($GLOBALS['current_dir'] . 'update-log.txt'));
			break;
	}
};

$ws->onClose = function($client) {

};

$ws->start(function ($client) {
	
});

\Swoole\Process::daemon();
